package com.layblog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.layblog.common.lang.Result;
import com.layblog.service.ElasticSearchService;
import com.layblog.vo.PostVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.PostConstruct;

/**
 * 超级管理员控制层
 * <p>
 * 数据同步的操作我们放在后台管理,需要超级管理员，先将所有的数据查找出来，再同步到es中
 *
 * @Author 林必昭
 * @Date 2021/9/8 15:16
 */

@Slf4j
@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {

    @Autowired
    ElasticSearchService searchService;

    @ResponseBody
    @PostMapping("/initEsData")
    @PostConstruct
    public Result initEsData() {

        log.info("--------------------- 初始化ES索引库数据开始 -------------------");

        int total = 0;

        Page page = new Page<>();
        int size = 1000;

        for (int i = 1; i < 1000; i++) {
            page.setCurrent(i);
            page.setSize(size);
            IPage<PostVO> pageData = postService.paging(page, null, null, null, null, "created");
            int num = searchService.initEsData(pageData.getRecords());

            total += num;
            //当查询的数据比每页的数量少时说明是最后一页，这个时候break结束
            if (num < size) {
                break;
            }
        }
        return Result.succ("初始化ES索引库数据成功，共：" + total + "条数据", null);
    }

}
